package cn.jhc.teachingquality.util;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import com.android.volley.NetworkError;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;

import cn.jhc.teachingquality.Global;
import cn.jhc.teachingquality.net.LoginRequest;
import cn.jhc.teachingquality.net.RequestQueueFactory;
import cn.jhc.teachingquality.rx.RxBus;

import static cn.jhc.teachingquality.Global.LOG_TAG;

/**
 * Created by luyanfei on 16-6-10.
 */
public class AuthUtils {

    public static void performLogin(final Context context, String username, String password) {
        LoginRequest loginRequest = new LoginRequest(username, password, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                RxBus.getInstance().post(Global.LOGIN_SUCCEED_IN_BACKGROUND);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                if (error instanceof TimeoutError || error instanceof NetworkError) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    AlertDialog dialog = builder.setTitle("网络错误")
                            .setMessage("网络出问题了，请检查！")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    RxBus.getInstance().post(Global.NETWORK_FAILURE);
                                }
                            })
                            .create();
                    dialog.show();
                    return;
                }
                Log.w(LOG_TAG, "Status code: " + error.networkResponse.statusCode);
                Log.w(LOG_TAG, "Network roundtrip time: " + error.networkResponse.networkTimeMs);
            }
        });

        RequestQueueFactory.getRequestQueue(context.getApplicationContext()).add(loginRequest);
    }
}
